//
//  Router.swift
//  CodingTest
//
//  Created by LYPC on 2021/11/19.
//

import UIKit

public protocol RouterPathable {
    var any: AnyClass { get }
    var params: RouterParam? { get }
}

public protocol RouterParam { }

public protocol Routable {
    static func initWithRouter(params: RouterParam?) -> UIViewController?
}

public class Router<Path: RouterPathable> { }

/// for controllers
public extension Router {
    static func open(_ path: Path,
                     animated: Bool = true,
                     useNav navVC: UINavigationController? = nil,
                     isPresent: Bool = false,
                     presentingVC: UIViewController? = UIViewController.currentVC) {
        DispatchQueue.main.safeAsync {
            if let cls = path.any as? Routable.Type,
                let vc = cls.initWithRouter(params: path.params) {
                
                if !isPresent {
                    p_show(vc: vc, animated: animated, navVC: navVC)
                } else {
                    presentingVC?.present(vc, animated: animated)
                }
            } else {
                k_log("🔴 error router path")
            }
        }
    }
    
    private static func p_show(vc: UIViewController,
                               animated: Bool = true,
                               navVC: UINavigationController? = nil) {
        if let nav = navVC,
            vc.navigationController == nil {
            nav.pushViewController(vc, animated: animated)
        }
        else if let topVC = UIViewController.currentVC,
             let nav = topVC.navigationController,
             vc.navigationController == nil {
            nav.pushViewController(vc, animated: animated)
        }
    }
    
    static func close() {
        DispatchQueue.main.safeAsync {
            let topViewController = UIApplication.currentVC
            if let nav = topViewController?.navigationController {
                nav.popViewController(animated: true)
            } else {
                topViewController?.dismiss(animated: true, completion: nil)
            }
        }
    }
}

public class Router_none: UIViewController { }

extension Router_none: Routable {
  
    public static func initWithRouter(params: RouterParam?) -> UIViewController? {
        return nil
    }
}

